""" 

    Youtube.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page is a webservice which takes a list of Ids and returns a list of the 3 most recent
    YouTube videos posted on their YouTube account as a JSON object
    
    Accepts one parameter:
        ids (required) - comma delimited list of Bioguide Ids
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import wsgiref.handlers
import const
import facebook
from datetime import datetime

from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
        
from utils import fbUtil, SunlightUtil, memcacheUtil, textUtil

import gdata.youtube
import gdata.youtube.service
import gdata.service
import gdata.urlfetch

# Use urlfetch instead of httplib
gdata.service.http_request_handler = gdata.urlfetch

class MainHandler(webapp.RequestHandler):

    def get(self):
        self.post()
        
    def post(self):
        
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"
        jsonOutput = {"result":"ok", "message":"", "video":[]}
        
        theIds = self.request.get('ids', default_value=None)
            
        if theIds is not None:
            
            yt_service = gdata.youtube.service.YouTubeService()
            yt_service.developer_key = const.YOUTUBE_API_KEY
            yt_service.client_id = const.YOUTUBE_CLIENT_ID
            legislatorIds = theIds.split(",") 
            memcache = memcacheUtil()  
            sunlight = SunlightUtil(const.SUNLIGHT_API_KEY)
            
            # get the info about extended permissions
            try:
                self.facebookapi = fbUtil().checkFacebookAppInstalled(self, False)
                if self.facebookapi is None:
                    jsonOutput["loggedin"] = False
                else:
                    jsonOutput["loggedin"] = True
                    jsonOutput["linkPermission"] = self.facebookapi.users.hasAppPermission("share_item")                
            except facebook.FacebookError, e:
                jsonOutput["loggedin"] = False
                      
            for legislatorId in legislatorIds:
                legislator = sunlight.apicall("legislators.get", {"bioguide_id": legislatorId})
                
                if legislator is not None:
                    youtube_url = legislator["legislator"]["youtube_url"]
                    youtube_username = youtube_url.rsplit("/", 1)[1]
                    gdata_url = 'http://gdata.youtube.com/feeds/api/users/%s/uploads' % youtube_username
                    #self.response.out.write(gdata_url)
                    feed = yt_service.GetYouTubeVideoFeed(gdata_url)
                    for entry in feed.entry:
                        url = entry.GetHtmlLink()
                        if url is not None:
                            tempVideo = {"url": url.href, "date": entry.published.text,"name": const.FRIENDLY_NAME[legislatorId], "title": const.FRIENDLY_NAME[legislatorId] + " - " + entry.media.title.text, "description": entry.media.description.text, "thumbnail":""}
                            if len(entry.media.thumbnail) > 0:
                                tempVideo["thumbnail"] = entry.media.thumbnail[0].url
                            jsonOutput["video"].append(tempVideo)
                    
        else:
            jsonOutput["result"] = "error"
            jsonOutput["message"] = "missing IDs"
                
                       
        self.response.out.write(simplejson.dumps(jsonOutput))    
        
        
def main():
    application = webapp.WSGIApplication([('/fb/youtube', MainHandler)],
                                       debug=True)
    run_wsgi_app(application)
                                       

if __name__ == '__main__':
    main()
